package service

import (
	"blog-server/global"
	"blog-server/models"
	"blog-server/models/views"
	"blog-server/utils/msg"
	"github.com/sirupsen/logrus"
	"time"
	"xorm.io/xorm"
)

type CommentService struct{}

func NewCommentService() *CommentService {
	return &CommentService{}
}

// CommentList  条件查询评论列表  （后台）
func (c *CommentService) CommentList(param views.AdminCommentRespVo) (*msg.DataPage, error) {
	condition := func(session *xorm.Session) *xorm.Session {
		session = session.Where("can_view = true")
		if param.Start != "" && param.End == "" {
			session = session.Where("date_format(create_time,'%Y-%m-%d') >= ?", param.Start)
		}
		if param.Start == "" && param.End != "" {
			session = session.Where("date_format(create_time,'%Y-%m-%d') <= ?", param.End)
		}
		if param.Start != "" && param.End != "" {
			session = session.Where("create_time >= ?", param.Start).Where("create_time <= ?", param.End)
		}
		return session
	}

	var data []models.Comment

	if param.Page <= 0 {
		param.Page = 1
	}
	if param.Size <= 0 {
		param.Size = 10
	}

	err := condition(global.Engine.Table(&models.Comment{})).Desc("create_time").Limit(param.Size, (param.Page-1)*param.Size).Find(&data)
	if err != nil {
		logrus.Errorf("条件查询评论列表:查询数据列表失败 => %s\n", err)
		return nil, msg.NewSysError(err.Error())
	}

	count, err := condition(global.Engine.Table(&models.Comment{})).Count()
	if err != nil {
		logrus.Errorf("条件查询评论列表:统计数据失败 => %s\n", err)
		return nil, msg.NewSysError(err.Error())
	}
	return msg.NewDataPage(data, count, param.Page, param.Size), nil

}

// CommentBatchDel 批量删除数据
func (c *CommentService) CommentBatchDel(ids []string) (int64, error) {
	tx := global.Engine.NewSession()
	err := tx.Begin()
	num, err := tx.Table(&models.Comment{}).In("is", ids).Update(map[string]interface{}{"can_view": false, "update_time": time.Now()})
	if err != nil {
		err = tx.Rollback()
	} else {
		return num, nil
	}
	err = tx.Commit()

	defer func(tx *xorm.Session) {
		if err != nil {
			logrus.Errorf("批量删除评论数据失败：%s，进行回滚\n", err)
			err := tx.Rollback()
			if err != nil {
				return
			}
		}
		err = tx.Close()
		if err != nil {
			logrus.Errorf("批量删除评论数据，关闭事务失败：%s\n", err)
			return
		}
	}(tx)
	return 0, err
}

func (c *CommentService) CommentByArticle(id int64) {

}
